package com.zx.mes.hyl.upms.service.impl;

import com.zx.mes.hyl.common.pagemodel.DataGrid;
import com.zx.mes.hyl.common.pagemodel.LayPageHelper;
import com.zx.mes.hyl.common.pagemodel.PageHelper;
import com.zx.mes.hyl.common.pagemodel.SessionInfo;
import com.zx.mes.hyl.common.util.MD5Util;
import com.zx.mes.hyl.upms.dao.RoleRepository;
import com.zx.mes.hyl.upms.dao.UserRepository;
import com.zx.mes.hyl.upms.model.Tresource;
import com.zx.mes.hyl.upms.model.Trole;
import com.zx.mes.hyl.upms.model.Tuser;
import com.zx.mes.hyl.upms.pagemodel.User;
import com.zx.mes.hyl.upms.service.UserServiceI;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

/**
 * @author hyl
 */
@Service
public class UserServiceImpl implements UserServiceI {


    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoleRepository roleRepository;


    @Override
    public User login(User user) {
        Tuser t =userRepository.findByNameAndPwd(user.getName(),user.getPwd());
        if (t != null) {
            BeanUtils.copyProperties(t, user);
            return user;
        }
        return null;
    }

    @Override
    synchronized public void reg(User user) throws Exception {
        Tuser t =userRepository.findByNameAndPwd(user.getName(),user.getPwd());
        if (t!=null && ! "".equalsIgnoreCase(t.getId())) {
            throw new Exception("登录名已存在！");
        } else {
            Tuser u = new Tuser();
            u.setId(UUID.randomUUID().toString());
            u.setName(user.getName());
            u.setPwd(MD5Util.md5(user.getPwd()));
            u.setCreatedatetime(new Date());
            userRepository.save(u);
        }
    }

    @Override
    public List<User> findAll(User user, LayPageHelper ph) {
        List<User> ul = new ArrayList<>();

        Pageable pageable=new PageRequest(ph.getPage()-1, ph.getLimit());
        List<Tuser> tuserList=userRepository.findAll(getSpec(user),pageable).getContent();

        returnList(ul, tuserList);
        return ul;
    }

    private void returnList(List<User> ul, List<Tuser> tuserList) {
        if (tuserList != null && tuserList.size() > 0) {
            for (Tuser t : tuserList) {
                User u = new User();
                BeanUtils.copyProperties(t, u);
                Set<Trole> roles = t.getTroles();
                if (roles != null && !roles.isEmpty()) {
                    String roleIds = "";
                    String roleNames = "";
                    boolean b = false;
                    for (Trole tr : roles) {
                        if (b) {
                            roleIds += ",";
                            roleNames += ",";
                        } else {
                            b = true;
                        }
                        roleIds += tr.getId();
                        roleNames += tr.getName();
                    }
                    u.setRoleIds(roleIds);
                    u.setRoleNames(roleNames);
                }
                ul.add(u);
            }
        }
    }

    @Override
    public long count(User user) {

        return userRepository.count(getSpec(user));
    }

    private Specification<Tuser> getSpec(User user) {
        return new Specification<Tuser>() {
            @Override
            public Predicate toPredicate(Root<Tuser> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList=new ArrayList<>();
                if (user.getName()!=null && ! user.getName().equalsIgnoreCase("")){
                    predicateList.add(cb.like(root.get("name").as(String.class),"%"+user.getName()+"%"));
                }
                if (user.getCreatedatetimeStart()!=null){
                    predicateList.add(cb.greaterThanOrEqualTo(root.get("createdatetime").as(Date.class),user.getCreatedatetimeStart()));
                }
                if (user.getCreatedatetimeEnd()!=null){
                    predicateList.add(cb.greaterThanOrEqualTo(root.get("createdatetime").as(Date.class),user.getCreatedatetimeEnd()));
                }

                query.where(predicateList.toArray(new Predicate[predicateList.size()]));
                return null;
            }
        };
    }

    @Override
    public DataGrid dataGrid(User user, PageHelper ph) {
        //创建查询条件数据对象
        DataGrid dg = new DataGrid();
        List<User> ul = new ArrayList<>();

        Pageable pageable=new PageRequest(ph.getPage()-1, ph.getRows());
        List<Tuser> tuserList=userRepository.findAll(getSpec(user),pageable).getContent();

        returnList(ul, tuserList);
        dg.setRows(ul);
        dg.setTotal(userRepository.count());
        return dg;
    }

    @Override
    public void add(User user) throws Exception {
        reg(user);
    }

    @Override
    public User get(String id) {
        Tuser t = userRepository.getByUserId(id);
        User u = new User();
        BeanUtils.copyProperties(t, u);
        if (t.getTroles() != null && !t.getTroles().isEmpty()) {
            String roleIds = "";
            String roleNames = "";
            boolean b = false;
            for (Trole role : t.getTroles()) {
                if (b) {
                    roleIds += ",";
                    roleNames += ",";
                } else {
                    b = true;
                }
                roleIds += role.getId();
                roleNames += role.getName();
            }
            u.setRoleIds(roleIds);
            u.setRoleNames(roleNames);
        }
        return u;
    }

    @Override
    public User getByUserName(String name) {
//        Tuser t = userRepository.findByName(name);
//        User u = new User();
//        BeanUtils.copyProperties(t, u);
        return null;
    }

    @Override
    synchronized public void edit(User user) throws Exception {
//        Tuser t=userRepository.findByName(user.getName());
//
//        if ( t!=null && ! "".equalsIgnoreCase(t.getId())) {
//            throw new Exception("登录名已存在！");
//        } else {
//            Tuser u = userRepository.getOne(user.getId());
//            BeanUtils.copyProperties(user, u, new String[] { "pwd", "createdatetime" });
//            u.setModifydatetime(new Date());
//        }
    }

    @Override
    public void delete(String id) {
        userRepository.delete(userRepository.getOne(id));
    }

    @Override
    public void grant(String ids, User user) {
        if (ids != null && ids.length() > 0) {
            List<Trole> roles = new ArrayList<Trole>();
            if (user.getRoleIds() != null) {
                for (String roleId : user.getRoleIds().split(",")) {
                    roles.add(roleRepository.getOne(roleId));
                }
            }
            for (String id : ids.split(",")) {
                if (id != null && !id.equalsIgnoreCase("")) {
                    Tuser t = userRepository.getOne(id);
                    t.setTroles(new HashSet<Trole>(roles));
                }
            }
        }
    }

    @Override
    public List<String> resourceList(String id) {
        List<String> resourceList = new ArrayList<String>();
        Tuser t =userRepository.getResourceByUserId(id);
        if (t != null) {
            Set<Trole> roles = t.getTroles();
            if (roles != null && !roles.isEmpty()) {
                for (Trole role : roles) {
                    Set<Tresource> resources = role.getTresources();
                    if (resources != null && !resources.isEmpty()) {
                        for (Tresource resource : resources) {
                            if (resource != null && resource.getUrl() != null) {
                                resourceList.add(resource.getUrl());
                            }
                        }
                    }
                }
            }
        }
        return resourceList;
    }

    @Override
    public void editPwd(User user) {
        if (user != null && user.getPwd() != null && !"".equalsIgnoreCase(user.getPwd().trim())) {
            Tuser u = userRepository.getOne(user.getId());
            u.setPwd(MD5Util.md5(user.getPwd()));
            u.setModifydatetime(new Date());
        }
    }

    @Override
    public boolean editCurrentUserPwd(SessionInfo sessionInfo, String oldPwd, String pwd) {
        Tuser u = userRepository.getOne(sessionInfo.getId());
        // 说明原密码输入正确
        if (u.getPwd().equalsIgnoreCase(MD5Util.md5(oldPwd))) {
            u.setPwd(MD5Util.md5(pwd));
            u.setModifydatetime(new Date());
            return true;
        }
        return false;
    }

    @Override
    public List<User> loginCombobox(String q) {
        if (q == null) {
            q = "";
        }


//        List<Tuser> tl = userRepository.findByNameLike(q.trim(),new PageRequest(0,10));
//        List<User> ul = new ArrayList<>();
//        if (tl != null && tl.size() > 0) {
//            for (Tuser t : tl) {
//                User u = new User();
//                u.setName(t.getName());
//                ul.add(u);
//            }
//        }
        return null;
    }

    @Override
    public DataGrid loginCombogrid(String q, PageHelper ph) {
        if (q == null) {
            q = "";
        }
        DataGrid dg = new DataGrid();
        List<User> ul = new ArrayList<>();

//        List<Tuser> tl = userRepository.findByNameLike(q.trim(),new PageRequest(ph.getPage()-1,ph.getRows()));
//        if (tl != null && tl.size() > 0) {
//            for (Tuser t : tl) {
//                User u = new User();
//                u.setName(t.getName());
//                u.setCreatedatetime(t.getCreatedatetime());
//                u.setModifydatetime(t.getModifydatetime());
//                ul.add(u);
//            }
//        }
        dg.setRows(ul);
        dg.setTotal(userRepository.count());
        return dg;
    }

    @Override
    public List<Long> userCreateDatetimeChart() {
        return null;
    }
}
